package org.iks.gfs.business.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.iks.common.exception.BusinessException;
import org.iks.gfs.exception.GfsFileNotFoundException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;

/**
 * Author kzou
 * Date 2024/2/14
 * Description:
 */
@Slf4j
@Service
public class GfsService {

    @Value("${files.upload.path}")
    private String savePath;

    public String uploadFile(MultipartFile multipartFile)  {
        String originalFilename = multipartFile.getOriginalFilename();
        String type = FileUtil.extName(originalFilename);
        String fileName = RandomUtil.randomString(8) + "." + type;
        File file = new File(savePath + "/" + fileName);
        if (!file.getParentFile().exists()) {
            boolean res = file.getParentFile().mkdirs();
            if (res) {
                log.info("mkdir upload dir: " + file.getParentFile().getAbsolutePath());
            } else {
                log.warn("mkdir upload dir error: " + file.getParentFile().getAbsolutePath());
            }
        }
        try {
            multipartFile.transferTo(file.getAbsoluteFile());
        } catch (IOException e) {
            log.error("文件上传失败： {}", e.getMessage());
            throw new BusinessException("upload error");
        }
        return fileName;
    }

    public byte[] loadImage(String fileName) throws IOException{
        File file = new File(savePath + "/" + fileName);
        try (FileInputStream fileInputStream = new FileInputStream(file)) {
            return fileInputStream.readAllBytes();
        } catch (FileNotFoundException e) {
            log.error("未找到指定的文件： {}", fileName);
            throw new GfsFileNotFoundException();
        }
    }

    public List<Integer> sliceUpload(MultipartFile multipartFile, Integer index, Integer maxIndex, String fileName) {
        String sliceSavePath = savePath + "/slice/" + fileName.substring(0, fileName.lastIndexOf(".") - 1);
        File savePath = new File(sliceSavePath);
        File tmpFile = new File(sliceSavePath + "/" + index + "-" + fileName);
        File[] files = savePath.listFiles();
        List<Integer> existSlice = Collections.emptyList();
        try {
            multipartFile.transferTo(tmpFile.getAbsoluteFile());
        } catch (IOException e) {
            log.warn("save file error {}", e.getMessage());
        }
        if (files != null && files.length > 0) {
            existSlice =Arrays.stream(files)
                    .map(File::getName)
                    .map(e -> e.substring(0, e.indexOf('-') - 1))
                    .map(Integer::parseInt)
                    .sorted((Comparator.comparingInt(e -> e)))
                    .toList();
        }
        if (existSlice.size() == maxIndex && Objects.equals(existSlice.getLast(), maxIndex)) {
            // 文件合并

        }
        return existSlice;
    }
}




